<template>
  <div class="container">
    <div class="content-wrapper">
      <!-- 子组件 -->
      <audio-player
        :input-text="currentWord"
        :repeat="3"
        @play-end="handlePlayEnd"
        ref="audioPlayerRef"
      />

      <!-- 骨架屏 -->
      <div v-if="isLoading" class="skeleton-container">
        <el-skeleton animated :count="1">
          <template #template>
            <div style="padding: 14px">
              <el-skeleton-item variant="image" style="width: 100%; height: 240px" />
              <div style="display: flex; align-items: center; margin-top: 8px">
                <el-skeleton-item variant="text" style="margin-right: 16px; width: 100px" />
                <el-skeleton-item variant="text" style="width: 50%" />
              </div>
            </div>
          </template>
        </el-skeleton>
      </div>

      <!-- 图片展示 -->
      <div v-else>
        <ImageGallery :images="galleryImages" />
        <el-empty v-if="!galleryImages.length" description="无图片数据" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import AudioPlayer from '@/components/AudioPlayer.vue'
import ImageGallery from '@/components/ImageGallery.vue'
import type { Word } from '@/types/training'

interface ImageData {
  url: string
  alt: string
  aspectRatio: string
  caption: string
}

interface ImageResponse {
  url: string
  alt?: string
  aspectRatio?: string
  caption?: string
}

interface Props {
  audio: {
    words: Word[]
  }
  images: {
    words: Word[]
  }
}

const props = withDefaults(defineProps<Props>(), {
  audio: () => ({
    words: [] as Word[],
  }),
  images: () => ({
    words: [] as Word[],
  }),
})

const emit = defineEmits<{
  (e: 'complete'): void
}>()

// 状态管理
const currentWord = ref(props.audio.words[0].text || '')
const currentImage = ref(props.images.words[0].text || '')
const galleryImages = ref<ImageData[]>([])
const isLoading = ref(false)
const audioPlayerRef = ref<InstanceType<typeof AudioPlayer> | null>(null)

// 获取对应单词的图片
const fetchImages = async () => {
  if (!currentImage.value) return

  isLoading.value = true
  try {
    const response = await axios.post(
      `/api/pic/getUrl?prompt=${encodeURIComponent(currentImage.value)}`,
    )
    galleryImages.value = response.data.map((image: ImageResponse) => ({
      url: image.url,
      alt: image.alt || '示例图片',
      aspectRatio: image.aspectRatio || '1/1',
      caption: image.caption || '',
    }))
  } catch (error) {
    console.error('获取图片失败:', error)
    galleryImages.value = []
    ElMessage.error('获取图片失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 处理音频播放结束
const handlePlayEnd = () => {
  emit('complete')
}

// 初始化加载
onMounted(async () => {
  if (currentWord.value || currentImage.value) {
    await fetchImages()
    // 自动播放第一个音频
    if (audioPlayerRef.value && 'play' in audioPlayerRef.value) {
      ;(audioPlayerRef.value as { play: () => void }).play()
    }
  }
})
</script>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  padding: 12px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content-wrapper {
  width: 100%;
  max-width: 800px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.skeleton-container {
  background: #fff;
  border-radius: 12px;
  padding: 12px;
  margin-top: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* iPhone 特定样式 */
@supports (-webkit-touch-callout: none) {
  .container {
    padding-bottom: env(safe-area-inset-bottom);
  }
}

/* 横屏模式 */
@media screen and (orientation: landscape) {
  .content-wrapper {
    flex-direction: row;
    align-items: flex-start;
    gap: 24px;
  }
}

/* 小屏幕设备 */
@media screen and (max-width: 375px) {
  .container {
    padding: 8px;
  }

  .content-wrapper {
    gap: 12px;
  }
}
</style>
